// Package repository
// @Author: zhangdi
// @File: user_tool
// @Version: 1.0.0
// @Date: 2023/5/17 17:47
package repository

import (
	"errors"
	"gorm.io/gorm"
	"ideatools/application/db/dbdto"
	"ideatools/application/db/entity"
	"ideatools/application/db/sqllite"
	"ideatools/application/pkgs/utils"
	"ideatools/application/pkgs/where"
	"strconv"
)

type ConfigRepository struct {
	db *gorm.DB
}

func NewConfigRepository(db *gorm.DB) *ConfigRepository {
	return &ConfigRepository{db}
}

// Create 创建用户工具
func (r *ConfigRepository) Create(dtoConfig *dbdto.ConfigAdd) error {
	//加锁
	sqllite.Mutex.Lock()
	defer sqllite.Mutex.Unlock()

	entityConfig := new(entity.Config)         //为分配一个内存空间
	utils.DtoToEntity(dtoConfig, entityConfig) //将dto转成entity
	result := r.db.Create(entityConfig)
	return result.Error
}

// UpdateValue 更新值
func (r *ConfigRepository) UpdateValue(key string, value string, typ string) error {
	//加锁
	sqllite.Mutex.Lock()
	defer sqllite.Mutex.Unlock()

	tx := r.db.Model(&entity.Config{}).Where("config_key = ?", key).Update("config_value", value)
	if tx.Error == nil {
		//设置type
		r.db.Model(&entity.Config{}).Where("config_key = ?", key).Update("config_type", typ)
	}
	return tx.Error
}

// Update 更新用户工具
func (r *ConfigRepository) Update(dtoConfig *dbdto.ConfigUpdate) error {
	//加锁
	sqllite.Mutex.Lock()
	defer sqllite.Mutex.Unlock()

	entityConfig := new(entity.Config)         //为分配一个内存空间
	utils.DtoToEntity(dtoConfig, entityConfig) //将dto转成entity
	result := r.db.Save(entityConfig)
	if result.RowsAffected == 0 {
		return gorm.ErrRecordNotFound
	}
	return result.Error
}

// FindOneByWhere 根据FieldValue查询一条数据：
func (r *ConfigRepository) FindOneByWhere(wheres []*where.Field) (*entity.Config, error) {
	var result *entity.Config
	whereStr, whereValues, err := where.ConvertToGormWhere(wheres)
	if err != nil {
		return nil, err
	}
	if err := r.db.Where(whereStr, whereValues...).Find(&result).Error; err != nil {
		return nil, err
	}
	if result.Id < 1 {
		return nil, errors.New("查询结果为空，id=" + strconv.Itoa(int(result.Id)))
	}
	return result, nil
}

// FindListByWhere 根据FieldValue查询所有符合条件的数据列表：
func (r *ConfigRepository) FindListByWhere(wheres []*where.Field) ([]*entity.Config, error) {
	var resultList []*entity.Config
	whereStr, whereValues, err := where.ConvertToGormWhere(wheres)
	if err != nil {
		return nil, err
	}
	if err := r.db.Where(whereStr, whereValues...).Find(&resultList).Error; err != nil {
		return nil, err
	}
	return resultList, nil
}

func (r *ConfigRepository) DeleteByFieldValue(wheres []*where.Field) error {
	//加锁
	sqllite.Mutex.Lock()
	defer sqllite.Mutex.Unlock()

	whereStr, whereValues, err := where.ConvertToGormWhere(wheres)
	if err != nil {
		return err
	}
	if err := r.db.Where(whereStr, whereValues...).Delete(&entity.Config{}).Error; err != nil {
		return err
	}
	return nil
}
